package org.jeecg.modules.demo.issuingrecords.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.allvipcard.entity.AllVipcard;
import org.jeecg.modules.demo.allvipcard.service.IAllVipcardService;
import org.jeecg.modules.demo.basemembersharevip.entity.BaseMemberShareVip;
import org.jeecg.modules.demo.basemembersharevip.service.IBaseMemberShareVipService;
import org.jeecg.modules.demo.issuingrecords.entity.IssuingRecords;
import org.jeecg.modules.demo.issuingrecords.service.IIssuingRecordsService;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.vipcardcoupon.entity.VipCardCoupon;
import org.jeecg.modules.demo.vipcardcoupon.service.IVipCardCouponService;
import org.jeecg.modules.demo.vipcarddrawrecord.service.IVipcardDrawRecordService;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 发卡记录
 * @Author: jeecg-boot
 * @Date: 2022-01-07
 * @Version: V1.0
 */
@Api(tags = "发卡记录")
@RestController
@RequestMapping("/issuingrecords/issuingRecords")
@Slf4j
public class IssuingRecordsController extends JeecgController<IssuingRecords, IIssuingRecordsService> {

    @Autowired
    private IIssuingRecordsService issuingRecordsService;
    @Autowired
    private IAllVipcardService allVipcardService;
    @Autowired
    private IVipCardCouponService vipCardCouponService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IVipcardDrawRecordService vipcardDrawRecordService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页列表查询
     *
     * @param issuingRecords
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "发卡记录-分页列表查询")
    @ApiOperation(value = "发卡记录-分页列表查询", notes = "发卡记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(IssuingRecords issuingRecords,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "keyword", required = false) String keyword,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
//        req.getr
        Page<IssuingRecords> page = new Page<>(pageNo, pageSize);
        IPage<IssuingRecords> pageList = null;

        if (!StringUtils.isEmpty(issuingRecords.getStockId())) {
            QueryWrapper<IssuingRecords> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_id", storeId).eq("stock_id", issuingRecords.getStockId());
            pageList = issuingRecordsService.page(page, queryWrapper);
        } else {
            QueryWrapper<IssuingRecords> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_id", storeId);
            QueryGenerator.initQueryWrapper(queryWrapper, issuingRecords, req.getParameterMap());
            if (StringUtils.isNotEmpty(keyword)) {
                queryWrapper.and(q -> q.like("vip_name", keyword).or().like("member_name", keyword));
            }
            pageList = issuingRecordsService.page(page, queryWrapper);
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 为了保持返回值不变，沿用框架的分页方式。分页查询后用每项的商品id查项目详情
        List<IssuingRecords> records = pageList.getRecords();
        List<Map<String, Object>> records1 = records.stream().map(ir -> {
            Map<String, Object> m = ToolsUtils.objectToMap(ir);
            if (m.get("circulation") == null) {
                m.put("circulation", 0);
            }
            Integer circulation = (Integer) m.get("circulation");
            if (m.get("quantityReceived") == null) {
                m.put("quantityReceived", 0);
            }
            Integer quantityReceived = (Integer) m.get("quantityReceived");
            m.put("currentAllowance", circulation - quantityReceived);
            AllVipcard av = allVipcardService.getById(ir.getVipId());
            if (av != null) {
                m.put("cardId", av.getCardId());
                m.put("cardName", m.get("vipName"));
//                m.put("cardName", av.getCardName());
                m.put("cardType", av.getCardType());
                m.put("isFree", av.getIsFree());
                // 关联优惠劵数量
                List<VipCardCoupon> list = vipCardCouponService.list(new QueryWrapper<VipCardCoupon>()
                        .eq("store_id", storeId)
                        .eq("vip_id", av.getId()));
                Integer ticketNum = list.stream().map(VipCardCoupon::getNum).reduce(Integer::sum).orElse(0);
                m.put("ticketNum", ticketNum);
                av.setTicketNum(ticketNum);
                if ("付费".equals(av.getIsFree())) {
                    m.put("cardPrice", av.getSellingPrice());
                }
            }

            Date createTime = (Date) m.get("createTime");
            Date updateTime = (Date) m.get("updateTime");
            Date drawTime = (Date) m.get("drawTime");
            if (createTime != null) {
                m.put("createTime", sdf.format(createTime));
            }
            if (updateTime != null) {
                m.put("updateTime", sdf.format(updateTime));
            }
            if (drawTime != null) {
                m.put("drawTime", sdf.format(drawTime));
            }
            return m;
        }).collect(Collectors.toList());
        IPage<Map<String, Object>> pageList1 = new PageDTO<>();
        BeanUtils.copyProperties(pageList, pageList1);
        pageList1.setRecords(records1);
        return Result.OK(pageList1);
    }

    /**
     * 分页列表查询
     *
     * @param issuingRecords
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "发卡记录-分页列表查询")
    @ApiOperation(value = "发卡记录-分页列表查询", notes = "发卡记录-分页列表查询")
    @GetMapping(value = "/detail")
    public Result<?> queryPageDetailList(IssuingRecords issuingRecords,
                                         @RequestParam(name = "vipid", required = true, defaultValue = "") String vipid,
                                         @RequestParam(name = "memberName", required = false, defaultValue = "") String memberName,
                                         @RequestParam(name = "memberPhone", required = false, defaultValue = "") String memberPhone,
                                         @RequestParam(name = "enterStoreStatus", required = false, defaultValue = "") String enterStoreStatus,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         @RequestParam(name = "keyword", required = false) String keyword,
                                         HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        String vipId = vipid;
        if (StringUtils.isEmpty(vipId)) {
            return Result.error("请先到首页选择店铺");
        }
        String name = memberName;
        String phone = memberPhone;
        if (!StringUtils.isBlank(name)) {
            name = name.replaceAll("\\*", "");
        }
        if (!StringUtils.isBlank(phone)) {
            phone = phone.replaceAll("\\*", "");
        }

//        int count1 = issuingRecordsService.countMemVip(vipId);
//        int count2 = issuingRecordsService.countMemShareVip(vipId);
//        int count3 = issuingRecordsService.countMemReciveVip(vipId);
//
//        if (count1 > 0){
//            List<Map> maps = issuingRecordsService.listMemVip(vipId, name, phone, pageNo, pageSize);
//            Map<String, Object> result = new HashMap<>();
//            int total = issuingRecordsService.countVipEx(vipId,name,phone);
//            result.put("current",1);
//            result.put("total",total);
//            result.put("records",maps);
//            for (Map map: maps) {
//                if (map.get("enterStoreDate") != null){
//                    map.put("enterStoreDate","Y");
//                }else {
//                    map.put("enterStoreDate","N");
//                }
//            }
//            return Result.OK(result);
//        }else if (count2 >0) {
//            List<Map> maps = issuingRecordsService.listMemShareVip(vipId, name, phone, pageNo, pageSize);
//            Map<String, Object> result = new HashMap<>();
//            int total = issuingRecordsService.countVipEx(vipId,name,phone);
//            for (Map map: maps) {
//                if (map.get("enterStoreDate") != null){
//                    map.put("enterStoreDate","Y");
//                }else {
//                    map.put("enterStoreDate","N");
//                }
//            }
//
//            result.put("current",1);
//            result.put("total",total);
//            result.put("records",maps);
//            return Result.OK(result);
//
//        } else if (count3 > 0){
//            String shareMemeberIds = issuingRecordsService.getShareMemeberIds(vipId);
//            if (StringUtils.isEmpty(shareMemeberIds)){
//                return Result.error("没有分享数据");
//            }
//
//            String[] split = shareMemeberIds.split(",");
//            List<String> ids = new ArrayList<>();
//            Arrays.asList(ids);
//            List<Map> maps = issuingRecordsService.listMemReciveVip(ids, name, phone, pageNo, pageSize);
//            Map<String, Object> result = new HashMap<>();
//            int total = issuingRecordsService.countReciveVipEx(ids,name,phone);
//            for (Map map: maps) {
//                if (map.get("enterStoreDate") != null){
//                    map.put("enterStoreDate","Y");
//                }else {
//                    map.put("enterStoreDate","N");
//                }
//            }
//
//            result.put("current",1);
//            result.put("total",total);
//            result.put("records",maps);
//            return Result.OK(result);
//        }
//
//        String shareMemeberIds = issuingRecordsService.getShareMemeberIds(vipId);
//        List<String> ids = new ArrayList<>();
//        if (shareMemeberIds != null){
//            String[] split = shareMemeberIds.split(",");
//            ids = Arrays.asList(split);
//        }else{
//            ids.add("1");
//        }
        Map<String, Object> result = new HashMap<>();
//        IssuingRecords record = issuingRecordsService.getById(vipid);
////        String storeId = record.getStoreId();
//        vipId = record.getVipId();
        int total = issuingRecordsService.countDrawRecord(storeId, vipid, name, phone, enterStoreStatus);
        List<Map> maps = issuingRecordsService.listDrawRecord(storeId, vipid, name, phone, enterStoreStatus, pageNo, pageSize);

        for (Map map : maps) {
            if (map.get("enterStoreDate") != null) {
                map.put("enterStoreStatus", "1");
            } else {
                map.put("enterStoreStatus", "0");
            }
        }


        result.put("current", 1);
        result.put("total", total);
        result.put("records", maps);
        return Result.OK(result);
    }

    @AutoLog(value = "发卡记录-获取")
    @ApiOperation(value = "发卡记录-根据会员ID获取贵宾卡", notes = "发卡记录-根据会员ID获取贵宾卡")
    @GetMapping(value = "/listBySendId")
    public Result<?> listBySendId(String id,
                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                  HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<IssuingRecords> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("send_id", id);
        queryWrapper.eq("state", "2");
        Page<IssuingRecords> page = new Page<>(pageNo, pageSize);
        IPage<IssuingRecords> pageList = issuingRecordsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param issuingRecords
     * @return
     */
    @AutoLog(value = "发卡记录-添加")
    @ApiOperation(value = "发卡记录-添加", notes = "发卡记录-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> add(@RequestBody IssuingRecords issuingRecords, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        issuingRecords.setStoreId(storeId);
        issuingRecordsService.save(issuingRecords);
        return Result.OK("添加成功！");

    }

    /**
     * 编辑
     *
     * @param issuingRecords
     * @return
     */
    @AutoLog(value = "发卡记录-编辑")
    @ApiOperation(value = "发卡记录-编辑", notes = "发卡记录-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody IssuingRecords issuingRecords) {
        issuingRecordsService.updateById(issuingRecords);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "发卡记录-通过id删除")
    @ApiOperation(value = "发卡记录-通过id删除", notes = "发卡记录-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        issuingRecordsService.removeById(id);
        baseMemberShareVipService.deleteByRecordId(id);
        return Result.OK("删除成功!");
    }

    @Autowired
    private IBaseMemberShareVipService baseMemberShareVipService;

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "发卡记录-批量删除")
    @ApiOperation(value = "发卡记录-批量删除", notes = "发卡记录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.issuingRecordsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "发卡记录-通过id查询")
    @ApiOperation(value = "发卡记录-通过id查询", notes = "发卡记录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        IssuingRecords issuingRecords = issuingRecordsService.getById(id);
        if (issuingRecords == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(issuingRecords);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param issuingRecords
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, IssuingRecords issuingRecords) {
        return super.exportXls(request, issuingRecords, IssuingRecords.class, "发卡记录");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, IssuingRecords.class);
    }

}
